import { useEffect, useState, useRef } from 'react';
import { Button, Drawer, Progress, Spin } from 'antd';
import styles from './playGame.module.scss';
// import { handcardArr } from '../../util/mockcard';
import { MapRoleCardInfo, ReadTypeCardInfo } from '../../util/readCardMap';
import { RoleArray, EffectCardArray, EquipmentCardArray, LimitCardArray } from '../../util/playCardMock';

//卡组数据（所有卡）
const DeckData = [...RoleArray,...EffectCardArray, ...EquipmentCardArray, ...LimitCardArray]
DeckData.forEach(k => {
    let card_id = k.type_id + k.word_id + k.level_id + k.id + k.effect_id
    k.card_id = parseFloat(card_id)
})
//   //回合
//   roundCurrent: 0,
//   //开组
//   deckCard: [],
//   //手卡
//   handCard: [],
//   //效果区域（可盖牌显示效果卡，装备卡）
//   hideCard: [],
//   //使用历史
//   historyCard: [],
//   //等待状态
//   waitSwitch: false,


export default function PlayGameView({
    uuid,
    RoleArray,
    confirmHideCard,
    roundCurrent,
    waitSwitch,
    waitInfo,
    deckCard,
    handCard,
    hideCard,
    historyCard,
    deckCardAction,
    ambushCardAction,
    currentUseCardArrAcion,
    setCurrentJudge,
    currentJudge,
    endThisRound,
    myFraction,
    otherFraction,
    countDownNum,
    waitActionSwitch,
    waitUseCard,
    waitSaidTruth,
    confirmUpNoReplyArr
}) {

    const [selectItem, setSelectItem] = useState({
        showItemInfo: {},
        target: ''
    })
    const [undercoverCard, setUndercoverCard] = useState({})

    useEffect(() => {
        setUndercoverCard(uuid)
    }, [])
    useEffect(() => {
        console.log(waitUseCard)
    }, [waitUseCard])

    const lookActiveItemHandle = (item, target) => {
        setSelectItem({
            showItemInfo: item,
            target,
        })
    }

    const _ReadView = (flag) => {
        if (!Object.keys(flag).length) {
            return <div className={styles.seletHideCard}>
                <span className={styles.selectTitle}>{'请选择一张角色卡牌进行盖牌隐藏显示'}</span>
                <div className={styles.selectBox}>
                    {RoleArray.map((item, index) => {
                        return <div key={index}
                            className={styles.seletHideCardItem}>
                            <CardView
                                style={{
                                    width: '100%',
                                    height: '100%'
                                }}
                                showInfo
                                actionHandle={setUndercoverCard}
                                dataSource={item}
                                activeItem={undercoverCard}
                            />
                        </div>
                    })}
                </div>
                <div className={styles.buttonView}>
                    <Button onClick={() => setUndercoverCard({})} style={{ marginRight: 20 }} type={'default'}>{'重置选择'}</Button>
                    <Button onClick={() => confirmHideCard(undercoverCard)} type={'primary'}>{'提交确认'}</Button>
                </div>
            </div>
        } else {
            return <Spin spinning={roundCurrent==0?true:waitSwitch} tip={waitInfo?waitInfo:'等待状态...'}>
                <div className={styles.layoutBox}>
                    {waitActionSwitch&&<div style={{
                        marginLeft:waitUseCard.length?-(waitUseCard.length*180+40)/2:0
                    }} className={styles.waitActionBox}>
                        <div className={styles.waitActionBoxTit}><span>{`对方预言的真相是${waitSaidTruth},${waitUseCard&&waitUseCard.length?'请选择按顺序选择反击对方效果卡,对方的回合的出卡情况是:':'对方并没有发动效果卡'}`}</span></div>
                        <div className={styles.waitActionBoxCon}>
                            {waitUseCard&&waitUseCard.length&&waitUseCard.map((item,index)=>{
                                return <div key={index} style={{
                                    margin:6
                                }} className={styles.waitActionBoxConItem}>
                                                <CardView
                                                    style={{
                                                        width: '100%',
                                                        height: '100%',
                                                        color:'#fff'
                                                    }}
                                                    showInfo
                                                    dataSource={item}
                                                />
                                </div>
                            })}
                        </div>
                    </div>}
                    <div className={styles.actionBox}>
                        <ActionAreaView
                            ambushCardAction={ambushCardAction}
                            deckCardAction={deckCardAction}
                            currentUseCardArrAcion={currentUseCardArrAcion}
                            deckCardData={deckCard}
                            waitActionSwitch={waitActionSwitch}
                            looktargetDom={selectItem.target}
                            waitUseCard={waitUseCard}
                            data={selectItem.showItemInfo} />
                    </div>

                    <div className={styles.fightBox}>
                        <div className={styles.opponentView}>
                            <span>{`对手的信息区域摘要：对手效果取卡数剩余张,效果累计分数是${otherFraction}分`}</span>
                        </div>
                        <div className={styles.fightAea}>
                            <div className={styles.roundInfo}>
                                <span>{`当前是第${roundCurrent}回合`}</span>
                                {countDownNum>1?<span>{`倒数第几回合后将翻牌结算`}</span>:null}
                            </div>

                            <div className={styles.buffInfo}>

                                <span>{`当前效果累计分数为${myFraction}分`}</span>
                            </div>

                            <BattleZoneView
                                activeItem={selectItem.showItemInfo}
                                actionHandle={lookActiveItemHandle}
                                showData={hideCard}
                                undercoverCard={undercoverCard}
                            />

                        </div>
                        <HandCardView
                            actionHandle={lookActiveItemHandle}
                            // site={handcardArr[2].url}
                            cardArr={handCard}
                            show={true}
                            activeItem={selectItem.showItemInfo}
                        />
                    </div>

                    <div className={styles.historyBox}>
                      
                        <div className={styles.historyTitle}>
                            <span>{'历史记录'}</span>
                        </div>
                        <div className={styles.historyCardBox}>
                            {historyCard && historyCard.length ? historyCard.map((item, index) => <div key={index}
                                className={styles.historyCardItem}>
                                <CardView
                                    style={{
                                        width: '100%',
                                        height: '100%'
                                    }}
                                    showInfo
                                    dataSource={item}
                                />
                            </div>) : null}
                        </div>
                        <div className={styles.judge}>
                            <Button onClick={()=>{setCurrentJudge(1)}} type={currentJudge===1?'primary':'default'}>{'我的分数比对方大'}</Button>
                            <Button onClick={()=>{setCurrentJudge(2)}} type={currentJudge===2?'primary':'default'}>{'我的分数比对方小'}</Button>
                        </div>
                        {/* confirmUpNoReplyArr  */}

                      { waitActionSwitch? <div onClick={()=>confirmUpNoReplyArr&&confirmUpNoReplyArr()} className={styles.endEound}>
                            <span>{'结束本回合的反击操作'}</span>
                        </div>:<div onClick={()=>endThisRound&&endThisRound()} className={styles.endEound}>
                            <span>{'结束这个回合'}</span>
                        </div>}

                    </div>
                </div>
            </Spin>
        }
    }

    return (<div className={styles.gamingRoom}>

        {_ReadView(uuid)}
    </div>)
}




/**
 * 
 * @param {*} param0 
 * showInfo：是否展示卡牌
 * dataSource：卡牌对象
 * actionHandle：选择卡牌的处理
 * style：样式覆盖
 * activeItem：当前选择的卡牌
 * @returns 
 */

function CardView({ showInfo, dataSource, actionHandle, style, activeItem }) {

    //操作函数处理
    const _selectHandle = (data) => {
        if (actionHandle) {
            if (JSON.stringify(data) == JSON.stringify(activeItem)) {
                actionHandle({}, '')
            } else {
                actionHandle(data)
            }
        }
    }

    const readCardInfo=(data)=>{
        let  readNum=ReadTypeCardInfo(data.type,data.uuid)
        switch(data.type){
            case 'role':
                return data.info+`，该卡的能力值是${readNum}`
            case 'energy':
                return readNum>0?`为自己的积分增加${readNum}分`:`使对方的积分损失${readNum}分`
            case 'limit':
                return `使用此卡后，倒计时${readNum}回合翻开角色卡进行结算`
            case 'equipment':
                return readNum>0?`使用装备卡后，自己的角色增加${readNum}能力值`:`使用装备卡后，使对方的角色减少${readNum}能力值`
            default:
                return 0
        }
    }

    return <div style={{
        border: JSON.stringify(dataSource) == JSON.stringify(activeItem) ? `2px solid #00a9eb` : `2px solid #fff`,
        ...style
    }} onClick={() => _selectHandle(dataSource)}
        className={styles.VCardView}>
        <div style={{
            // backgroundImage: dataSource?.url ? `url(${dataSource.url})` : '',
            // backgroundSize: 'cover',
            // backgroundRepeat: 'no-repeat',
            borderBottom:'1px solid #888888',
            height:  '70%',
        }} className={styles.imgBox}>
            <span>{'绘画预设位置'}</span>
        </div>
        <div className={styles.captionBox}>
            <span>{readCardInfo(dataSource)}</span>
        </div>
        {/* {showInfo && <div className={styles.attributeBox}>
            <span>{'属性占位区域'}</span>
        </div>} */}
    </div>
}




/**
 * 
 * 
 * 效果卡区域
 */

function BattleZoneView({ activeItem, actionHandle, showData, undercoverCard }) {
    const _mockData = [1, 2, 3, 4]
    //查看卡牌以及选择盖牌进行操作处理
    const lookSelectItemHandle = (select) => {
        if (!Object.keys(select).length) {
            actionHandle && actionHandle({}, 'BattleZoneView')
            return
        }
        let index = showData.findIndex(k => k.uuid == select.uuid)
        if (index > -1) {
            actionHandle && actionHandle(showData[index], 'BattleZoneView')
        }
    }

    const lookRoleCardInfo = (item) => {
        actionHandle && actionHandle(item, 'role')
    }

    return <div className={styles.BattleZone}>
        <div className={styles.roleView}>
            <div className={styles.roleViewBox}>
                <CardView
                    style={{
                        width: '100%',
                        height: '100%',
                    }}
                    actionHandle={lookRoleCardInfo}
                    activeItem={activeItem}
                    showInfo={false}
                    dataSource={undercoverCard}
                />
            </div>
        </div>

        <div className={styles.hideCardView}>
            {showData && showData.length && showData.map((item, index) => {
                return <div key={item.uuid + index} className={styles.hideCardViewItem}>
                    <CardView
                        style={{
                            width: '100%',
                            height: '100%'
                        }}
                        actionHandle={lookSelectItemHandle}
                        activeItem={activeItem}
                        showInfo={false}
                        dataSource={item}
                    />
                </div>
            })}
        </div>

    </div>
}

/**
 * 
 * show:是否展示卡组信息 
 * show:是否展示卡组信息 
 * cardArr：渲染的手卡卡组数据
 * site：场地卡链接
 * actionHandle：选择卡牌处理
 * activeItem：当前被选中的卡牌
 * @returns 
 */

function HandCardView({ show, cardArr, site, actionHandle, activeItem }) {
    const back_url = 'https://hbimg.huabanimg.com/3f94864d0a678dd5c7d2bcf87680589b7a1450cf3a423-GHQY9B_fw658/format/webp'

    let back_item = { url: back_url }

    const backStyle = site ? {
        backgroundImage: `url(${site})`,
        backgroundSize: 'cover',
        backgroundRepeat: 'no-repeat',
    } : {
        backgroundColor: 'indianred'
    }

    const _HandCardselectHandle = (item) => {
        actionHandle && actionHandle(item, 'handCardView')
    }

    return <div style={{ justifyContent: show ? 'flex-start' : 'flex-end' }} className={styles.HandCard}>
        <div style={backStyle} className={styles.backImage} />
        <div className={styles.cardBox}>
            {cardArr.map((item, index) => <div className={styles.cardBoxItem} key={index}>
                <CardView
                    actionHandle={_HandCardselectHandle}
                    activeItem={activeItem}
                    showInfo={show}
                    dataSource={show ? item : back_item}
                />
            </div>)}
        </div>
    </div>
}

/**
 * 
 * data:卡牌对象
 * @returns 
 */
function ActionAreaView({ data, deckCardData, deckCardAction, ambushCardAction, currentUseCardArrAcion, looktargetDom,waitActionSwitch,waitUseCard }) {

    //种类(分类role1:角色卡,limit2:限制卡，site3:场地卡，energy4：能量卡,equipment5:装备卡)
    const renderActionView = (item) => {
        if(waitActionSwitch){
            switch (looktargetDom) {
                case 'role':
                    return []
                case 'BattleZoneView':
                    if(waitUseCard&&waitUseCard.length){
                        let buttonArr=[]
                        waitUseCard.forEach((k,i) => {
                            buttonArr.push({
                                name: `反击对方效果卡${i+1}}`, action: () => { currentUseCardArrAcion && currentUseCardArrAcion(item,looktargetDom,i) } 
                            })
                        });
                        return buttonArr
                    }else{
                        return []
                    }
                case 'handCardView':
                   return []
                default:
                    return []
            }
        }else{
            switch (looktargetDom) {
                case 'role':
                    return []
                case 'BattleZoneView':
                    return [
                        { name: '使用', action: () => { currentUseCardArrAcion && currentUseCardArrAcion(item,looktargetDom) } },
                    ]
                case 'handCardView':
                   return [
                        { name: '盖牌', action: () => { ambushCardAction && ambushCardAction(item) } },
                        { name: '使用', action: () => { currentUseCardArrAcion && currentUseCardArrAcion(item,looktargetDom) } },
                    ]
                default:
                    return []
            }
        }
      

    }

    return <div className={styles.ActionAreaView}>
        <div className={styles.cardSlot}>
            {Object.keys(data).length ? <CardView style={{
                width: '100%',
                height: '100%',
                margin: 0
            }}
                showInfo dataSource={data} /> : <span>{'选择卡牌'}</span>}
        </div>
        <div className={styles.menuView}>
            <div className={styles.title}>
                <span>{'操作选择'}</span>
            </div>
            <div className={styles.content}>
                {Object.keys(data).length ? renderActionView(data).map((item) => <Button onClick={() => item.action()} className={styles.ButtonMenu} key={item.name} type={'primary'}>{item.name}</Button>) : null}
            </div>
        </div>

        <div onClick={() => { deckCardAction && deckCardAction() }} className={styles.CardpileBox}>
            {deckCardData && <div className={styles.CardpileView}>
                <span style={{
                    fontWeight: 700,
                    fontSize: 20,
                    marginBottom: 16
                }}>{`卡组剩余:${deckCardData.length}张`}</span>
                <span>{`点击这个区域进行抽卡`}</span>
            </div>}
        </div>

    </div>
}



